﻿using System;
using System.Collections.Generic;
using BeefyEventAggregator;
using MATtutsLab.Entities;
using MATtutsLab.MVP.Events;
using MATtutsLab.MVP.Views;
using MATtutsLab.Repositories;

namespace MATtutsLab.MVP.Presenters
{
    public class ZombieMoviePresenter : IEventHandler<MovieUpdatedEvent>
    {
        protected IZombieMovieCatalogView View { get; set; }
        protected IMovieRepository Repository { get; set; }
        protected IEventPublisher EventPublisher { get; set; }
        protected IList<Movie> Movies { get; set; }
        protected Movie SelectedMovie { get; set; }
        protected Action<Movie> MovieDetailAction { get; set; }
        protected Action AddMovieAction { get; set; }
        protected Action<Movie> EditMovieAction { get; set; }

        public ZombieMoviePresenter(IZombieMovieCatalogView view, 
                                    IMovieRepository repository,
                                    IEventPublisher eventPublisher,
                                    Action<Movie> movieDetailAction, 
                                    Action addMovieAction, 
                                    Action<Movie> editMovieAction)
        {
            View = view;
            View.Presenter = this;

            Repository = repository;
            EventPublisher = eventPublisher;
            MovieDetailAction = movieDetailAction;
            AddMovieAction = addMovieAction;
            EditMovieAction = editMovieAction;
        }

        public void InitializeView()
        {
            Movies = Repository.GetAll();

            View.DisplayMovies(Movies);
            View.SelectFirstMovieInList();

            MovieSelected(SelectedMovie);
        }

        public void MovieSelected(Movie movie)
        {
            SelectedMovie = movie;

            if (movie != null)
                View.ShowMovieCoverImage(movie);
        }

        public void ViewDetailsRequested()
        {
            if (SelectedMovie != null)
                MovieDetailAction(SelectedMovie);
        }

        public void AddMovieRequested()
        {
            AddMovieAction();
        }

        public void EditMovieRequested()
        {
            if (SelectedMovie != null)
                EditMovieAction(SelectedMovie);
        }

        public void Handle(MovieUpdatedEvent eventData)
        {
            View.RefreshMovieList(Repository.GetAll(), eventData.Movie);
        }

        public void DeleteRequested()
        {
            if (SelectedMovie == null)
                return;

            if (View.PromptUserForDeleteConfirmation())
            {
                Repository.Delete(SelectedMovie);

                EventPublisher.Publish(new MovieUpdatedEvent(SelectedMovie));
            }
        }
    }
}